﻿using AvalonDock;
using AvalonDock.Layout;
using Commands;
using ICSharpCode.AvalonEdit.Highlighting;
using ICSharpCode.AvalonEdit.Highlighting.Xshd;
using SqLiteEditor.Forms;
using SqLiteEditor.Helper;
using SqLiteEditor.Properties;
using SqLiteEditor.Templates;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Data;
using System.Data.SQLite;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Xml;

namespace SqLiteEditor
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {

        private string FullFileNames = String.Empty;
        private CommandMap mCommands = new CommandMap();
        ObservableCollection<TTabelStructure> TableStructureDataSource = new ObservableCollection<TTabelStructure>();
        Dictionary<string, string> TableDML = new Dictionary<string, string>();
        List<string> TablesName = new List<string>();

        /// <summary>
        /// Get the list of commands
        /// </summary>
        public CommandMap Commands
        {
            get { return mCommands; }
        }

        public MainWindow()
        {
            InitializeComponent();

            DataContext = this;

            InitializeCommands();

            Application.Current.DispatcherUnhandledException += Current_DispatcherUnhandledException;

            TableDML.Clear();

        }

        #region ResetTree

        private void ResetTree()
        {
            PART_Tabels.Items.Clear();
            PART_Views.Items.Clear();
            PART_Indexes.Items.Clear();
            PART_Triggers.Items.Clear();
        }

        #endregion


        #region RefreshTree

        private void RefreshTree()
        {
            RefreshTables();
            RefreshViews();
            RefreshIndexes();
        }

        #endregion

        #region RefreshTables
        private void RefreshTables()
        {
            TableDML.Clear();

            PART_Tabels.Items.Clear();

            Tabels.Clear();

            DataRowCollection tabels = SqliteHelper.GetTabels();
            TabelsLabel = "Tabels (" + tabels.Count.ToString() + ")";

            foreach (DataRow tabel in tabels)
            {
                TreeViewItem treeViewItem = new TreeViewItem();
                treeViewItem.Header = tabel.ItemArray[2].ToString();
                treeViewItem.Tag = tabel;
                treeViewItem.ContextMenu = (ContextMenu)Resources["TabelContextMenu"];
                treeViewItem.ContextMenu.Tag = tabel.ItemArray[2].ToString();

                PART_Tabels.Items.Add(treeViewItem);

                Tabels.Add(tabel.ItemArray[2].ToString());

                List<TTabelStructure> columnFieldType = SqliteHelper.GetColumnFieldType(tabel.ItemArray[2].ToString());

                TableDML.Add(tabel.ItemArray[2].ToString(), SqliteHelper.GetDML(tabel));

                foreach (TTabelStructure fieldInfo in columnFieldType)
                {
                    TreeViewItem fieldInfoitem = new TreeViewItem();
                    fieldInfoitem.Header = fieldInfo.ToString();
                    fieldInfoitem.Tag = fieldInfo;

                    treeViewItem.Items.Add(fieldInfoitem);
                }

            }

        }

        #endregion

        #region RefreshViews
        private void RefreshViews()
        {

            PART_Views.Items.Clear();
            Views.Clear();

            DataRowCollection views = SqliteHelper.GetViews();

            ViewsLabel = "Views (" + views.Count.ToString() + ")";

            foreach (DataRow view in views)
            {
                Views.Add(view.ItemArray[2].ToString());

                TreeViewItem treeitem = new TreeViewItem();
                treeitem.Header = view.ItemArray[2].ToString();
                treeitem.Tag = treeitem;
                treeitem.ContextMenu = (ContextMenu)Resources["ViewContextMenu"];
                PART_Views.Items.Add(treeitem);
            }

        }
        #endregion

        #region RefreshIndexess

        private void RefreshIndexes()
        {
            PART_Indexes.Items.Clear();

            Indexes.Clear();

            DataRowCollection indexes = SqliteHelper.GetIndexes();

            IndexesLabel = "Indexes (" + indexes.Count.ToString() + ")";

            foreach (DataRow index in indexes)
            {
                Indexes.Add(index.ItemArray[5].ToString());

                TreeViewItem fieldInfoitem = new TreeViewItem();
                fieldInfoitem.Header = index.ItemArray[5].ToString();
                fieldInfoitem.Tag = index;
                fieldInfoitem.ContextMenu = (ContextMenu)Resources["IndexContextMenu"];
                PART_Indexes.Items.Add(fieldInfoitem);

            }

        }

        #endregion

        private void InitializeCommands()
        {
            #region cmdViewObjectWxplorer
            Commands.AddCommand("cmdViewObjectWxplorer", x =>
            {

                avalonObjectExplorer.Show();
            }
              );
            #endregion

            #region cmdLefttoRight
            Commands.AddCommand("cmdLefttoRight", x =>
            {
                ChangeFlowDirection(FlowDirection.LeftToRight);
            }
              );
            #endregion

            #region cmdRighttoLeft
            Commands.AddCommand("cmdRighttoLeft", x =>
            {
                ChangeFlowDirection(FlowDirection.RightToLeft);
            }
              );
            #endregion

            #region cmdSelectTopn
            Commands.AddCommand("cmdSelectTopn", x =>
            {
                SelectTopn();
            }
             );
            #endregion

            #region cmdEditData
            Commands.AddCommand("cmdEditData", x =>
            {
                EditData();
            }
             );
            #endregion

            #region cmdExecuteQuery
            Commands.AddCommand("cmdExecuteQuery", x =>
            {
                ExecuteCurrentQuery();
            }
             );
            #endregion

            #region cmdCreateNewDataBase
            Commands.AddCommand("cmdCreateNewDataBase", x =>
            {
                CreateNewDataBase();
            }
             );
            #endregion

            #region cmdConnectDataBase
            Commands.AddCommand("cmdConnectDataBase", x =>
            {
                ResetUI();
                OpenFiles();
            }
             );
            #endregion

            #region  cmdDisconnectDataBase
            Commands.AddCommand("cmdDisconnectDataBase", x =>
            {
                SqliteHelper.disConnect();
            }
             );
            #endregion

            #region cmdFontSize
            Commands.AddCommand("cmdFontSize", x =>
            {
                SetGridFontSize();
            }
             );
            #endregion

            #region cmdDesignTable
            Commands.AddCommand("cmdDesignTable", x =>
            {
                DesignTable();
            }
             );
            #endregion

            #region cmdNewTable
            Commands.AddCommand("cmdNewTable", x =>
            {
                AddNewTable();
            }
             );
            #endregion

            #region cmdDeleteTable
            Commands.AddCommand("cmdDeleteTable", x =>
            {
                DeleteTable();
            }
             );
            #endregion

            #region cmdRenameTable
            Commands.AddCommand("cmdRenameTable", x =>
            {
                RenameTable();
            }
             );
            #endregion

            #region cmdNewView
            Commands.AddCommand("cmdNewView", x =>
            {
                AddNewView();
            }
             );
            #endregion

            #region cmdDeleteView
            Commands.AddCommand("cmdDeleteView", x =>
            {
                DeleteView();
            }
             );
            #endregion

            #region cmdNewIndex
            Commands.AddCommand("cmdNewIndex", x =>
            {
                AddnewIndex();
            }
             );
            #endregion

            #region cmdDeleteIndex
            Commands.AddCommand("cmdDeleteIndex", x =>
            {
                DeleteIndex();
            }
             );
            #endregion

            #region cmdRenameIndex
            Commands.AddCommand("cmdRenameIndex", x =>
            {
                RenameIndex();
            }
             );
            #endregion

            #region cmdRefreshTree
            Commands.AddCommand("cmdRefreshTree", x =>
            {
                RefreshTree();
            }
             );
            #endregion

            #region cmdNewQuery
            Commands.AddCommand("cmdNewQuery", x =>
            {
                NewQuery();
            }
             );
            #endregion

            #region cmdSaveChanges
            Commands.AddCommand("cmdSaveChanges", x =>
            {
                SaveChanges();
            }
             );
            #endregion

            #region cmdShowAbout
            Commands.AddCommand("cmdShowAbout", x =>
            {
                ShowAbout();
            }
             );
            #endregion

            #region cmdExit
            Commands.AddCommand("cmdExit", x =>
            {
                Close();
            }
             );
            #endregion



        }

        private void ChangeFlowDirection(FlowDirection fllowdir)
        {
            var firstDocumentPane = dockManager.Layout.Descendents().OfType<LayoutDocumentPane>().FirstOrDefault();

            if (firstDocumentPane != null)
            {
                object obj = firstDocumentPane.SelectedContent;

                if (obj == null) return;

                if ((obj as LayoutDocument).Content is TBrowsWindow)
                {
                    ((obj as LayoutDocument).Content as TBrowsWindow).SetFlowDirection(fllowdir);
                }

                if ((obj as LayoutDocument).Content is TEditWindow)
                {
                    ((obj as LayoutDocument).Content as TEditWindow).SetFlowDirection(fllowdir);
                }
            }

        }

        private void ResetUI()
        {
            FullFileNames = String.Empty;
            TableStructureDataSource.Clear();

            TableDML.Clear();
            TablesName.Clear();

            Tabels.Clear();
            Views.Clear();
            Indexes.Clear();
            Triggers.Clear();

            ResetTree();
        }

        private void CreateNewDataBase()
        {
            // Configure open file dialog box
            Microsoft.Win32.SaveFileDialog dlg = new Microsoft.Win32.SaveFileDialog();
            dlg.FileName = ""; // Default file name

            dlg.Filter = "sqlite files (*.sqlite)|*.sqlite|db files (*.db)|*.db*|All files (*.*)|*.*";
            dlg.DefaultExt = "*.*"; // Default file extension
            dlg.FilterIndex = 3;
            dlg.InitialDirectory = @"D:\SqLiteEditor\SampleDb";//AppDomain.CurrentDomain.BaseDirectory;

            // Process open file dialog box results 
            if (dlg.ShowDialog().GetValueOrDefault())
            {
                FullFileNames = dlg.FileName;
                OpenDataBase(FullFileNames, dlg.SafeFileName, true);
            }

        }

        private void RenameIndex()
        {

            FrmRenameIndex frmRenameIndex = new FrmRenameIndex(GetCurrentSelectedIndex());

            if (frmRenameIndex.ShowDialog().Value)
            {
                string newName = frmRenameIndex.NewName;
                SqliteHelper.RenameIndex(frmRenameIndex.OldName, frmRenameIndex.NewName);
                RefreshIndexes();
            }
        }

        private void RenameTable()
        {

            FrmRenameTable frmRenameTable = new FrmRenameTable(GetCurrentSelectedtable());

            if (frmRenameTable.ShowDialog().Value)
            {
                string newName = frmRenameTable.NewName;
                SqliteHelper.RenameTable(frmRenameTable.OldName, frmRenameTable.NewName);
                RefreshTables();
            }
        }

        private void SaveChanges()
        {
            var firstDocumentPane = dockManager.Layout.Descendents().OfType<LayoutDocumentPane>().FirstOrDefault();

            if (firstDocumentPane != null)
            {

                object obj = firstDocumentPane.SelectedContent;

                if (obj == null) return;

                if (obj is LayoutDocument)
                {

                    TEditWindow EditWindow = (TEditWindow)(obj as LayoutDocument).Content;

                    if (EditWindow != null)
                    {

                        EditWindow.SaveChages();
                        StatusMessage = "Save Done ";
                    }
                }
            }
        }



        private void NewQuery()
        {
            var firstDocumentPane = dockManager.Layout.Descendents().OfType<LayoutDocumentPane>().FirstOrDefault();

            if (firstDocumentPane != null)
            {
                LayoutDocument laydoc = new LayoutDocument();

                TQueryWindow doc = new TQueryWindow();

                laydoc.Title = "Query " + (firstDocumentPane.Children.Count + 1).ToString();
                laydoc.Content = doc;

                firstDocumentPane.Children.Add(laydoc);

            }
        }

        public void AddNewTable()
        {
            FrmAddTable frmaddtable = new FrmAddTable();
            Nullable<bool> result = frmaddtable.ShowDialog();
            if (result.Value == true)
            {
                SqliteHelper.ExecuteNonQuery(frmaddtable.ResultQuery);
                RefreshTables();
            }
        }

        private void DeleteTable()
        {
            string TabelName = GetCurrentSelectedtable();
            SqliteHelper.DropTable(TabelName);
            RefreshTables();
        }

        public void AddNewView()
        {
            List<string> tablelist = SqliteHelper.GetTabelsName();

            FrmAddView frmaddview = new FrmAddView(tablelist);
            Nullable<bool> result = frmaddview.ShowDialog();
            if (result.Value == true)
            {
                InsertQuerytoQueryEditor(frmaddview.ResultQuery);
                ExecuteCurrentQuery();
                RefreshViews();
            }
        }

        public void DeleteView()
        {
            string ViewName = GetCurrentSelectedView();
            string query = SqliteHelper.Query_DropView(ViewName);
            InsertQuerytoQueryEditor(query);
            ExecuteNonQuery();
            RefreshViews();
        }

        public void AddnewIndex()
        {
            List<string> tablelist = SqliteHelper.GetTabelsName();

            FrmAddIndex frmaddindex = new FrmAddIndex(tablelist);
            Nullable<bool> result = frmaddindex.ShowDialog();
            if (result.Value == true)
            {
                SqliteHelper.ExecuteNonQuery(frmaddindex.ResultQuery);
                RefreshIndexes();
            }
        }

        public void DeleteIndex()
        {
            string IndexName = GetCurrentSelectedIndex();
            if (MessageBox.Show("Are You Sure ? ", "Warning", MessageBoxButton.YesNo, MessageBoxImage.Warning) == MessageBoxResult.Yes)
            {
                string query = SqliteHelper.Query_DropIndex(IndexName);
                SqliteHelper.ExecuteNonQuery(query);
                RefreshIndexes();
            }
        }

        private void SetGridFontSize()
        {
            ItemCollection items = mnuFontSize.Items;

            foreach (MenuItem item in items)
            {
                if (item.IsChecked)
                {
                    int fontsize = int.Parse(item.Tag as string);

                    GlobalOption.GlobalSettings.FontSize = fontsize;
                }
            }

            var firstDocumentPane = dockManager.Layout.Descendents().OfType<LayoutDocumentPane>().FirstOrDefault();

            if (firstDocumentPane != null)
            {
                object obj = firstDocumentPane.SelectedContent;

                if (obj == null) return;

                if ((obj as LayoutDocument).Content is TBrowsWindow)
                {
                    ((obj as LayoutDocument).Content as TBrowsWindow).SetFontSize(GlobalOption.GlobalSettings.FontSize);
                }

                if ((obj as LayoutDocument).Content is TEditWindow)
                {
                    ((obj as LayoutDocument).Content as TEditWindow).SetFontSize(GlobalOption.GlobalSettings.FontSize);
                }
            }


        }

        void Current_DispatcherUnhandledException(object sender, System.Windows.Threading.DispatcherUnhandledExceptionEventArgs e)
        {
            //MessageEdittor.Text = "Error : " + e.Exception.Message;
            e.Handled = true;
        }

        #region Dependency Property

        #region Indexes DependencyProperty

        public ObservableCollection<string> Tabels
        {
            get { return (ObservableCollection<string>)GetValue(TabelsProperty); }
            set { SetValue(TabelsProperty, value); }
        }


        public static readonly DependencyProperty TabelsProperty =
            DependencyProperty.Register("Tabels", typeof(ObservableCollection<string>), typeof(MainWindow), new PropertyMetadata(new ObservableCollection<string>()));

        #endregion

        #region Indexes DependencyProperty

        public ObservableCollection<string> Views
        {
            get { return (ObservableCollection<string>)GetValue(ViewsProperty); }
            set { SetValue(ViewsProperty, value); }
        }

        // Using a DependencyProperty as the backing store for Tables.  This enables animation, styling, binding, etc...
        public static readonly DependencyProperty ViewsProperty =
            DependencyProperty.Register("Views", typeof(ObservableCollection<string>), typeof(MainWindow), new PropertyMetadata(new ObservableCollection<string>()));

        #endregion

        #region Indexes DependencyProperty

        public ObservableCollection<string> Indexes
        {
            get { return (ObservableCollection<string>)GetValue(IndexesProperty); }
            set { SetValue(IndexesProperty, value); }
        }

        // Using a DependencyProperty as the backing store for Tables.  This enables animation, styling, binding, etc...
        public static readonly DependencyProperty IndexesProperty =
            DependencyProperty.Register("Indexes", typeof(ObservableCollection<string>), typeof(MainWindow), new PropertyMetadata(new ObservableCollection<string>()));

        #endregion

        #region Triggers DependencyProperty
        public ObservableCollection<string> Triggers
        {
            get { return (ObservableCollection<string>)GetValue(TriggersProperty); }
            set { SetValue(TriggersProperty, value); }
        }

        // Using a DependencyProperty as the backing store for Tables.  This enables animation, styling, binding, etc...
        public static readonly DependencyProperty TriggersProperty =
            DependencyProperty.Register("Triggers", typeof(ObservableCollection<string>), typeof(MainWindow), new PropertyMetadata(new ObservableCollection<string>()));

        #endregion

        public string DBFileName
        {
            get { return (string)GetValue(DBFileNameProperty); }
            set { SetValue(DBFileNameProperty, value); }
        }

        // Using a DependencyProperty as the backing store for DBFileName.  This enables animation, styling, binding, etc...
        public static readonly DependencyProperty DBFileNameProperty =
            DependencyProperty.Register("DBFileName", typeof(string), typeof(MainWindow), new PropertyMetadata(String.Empty));




        public string TabelsLabel
        {
            get { return (string)GetValue(TabelsLabelProperty); }
            set { SetValue(TabelsLabelProperty, value); }
        }

        // Using a DependencyProperty as the backing store for TabelsLabel.  This enables animation, styling, binding, etc...
        public static readonly DependencyProperty TabelsLabelProperty =
            DependencyProperty.Register("TabelsLabel", typeof(string), typeof(MainWindow), new PropertyMetadata("Tabels"));


        public string ViewsLabel
        {
            get { return (string)GetValue(ViewsLabelProperty); }
            set { SetValue(ViewsLabelProperty, value); }
        }

        // Using a DependencyProperty as the backing store for TabelsLabel.  This enables animation, styling, binding, etc...
        public static readonly DependencyProperty ViewsLabelProperty =
            DependencyProperty.Register("ViewsLabel", typeof(string), typeof(MainWindow), new PropertyMetadata("Views"));

        public string IndexesLabel
        {
            get { return (string)GetValue(IndexesLabelProperty); }
            set { SetValue(IndexesLabelProperty, value); }
        }

        // Using a DependencyProperty as the backing store for TabelsLabel.  This enables animation, styling, binding, etc...
        public static readonly DependencyProperty IndexesLabelProperty =
            DependencyProperty.Register("IndexesLabel", typeof(string), typeof(MainWindow), new PropertyMetadata("Indexes"));

        public string TriggersLabel
        {
            get { return (string)GetValue(TriggersLabelProperty); }
            set { SetValue(TriggersLabelProperty, value); }
        }

        // Using a DependencyProperty as the backing store for TabelsLabel.  This enables animation, styling, binding, etc...
        public static readonly DependencyProperty TriggersLabelProperty =
            DependencyProperty.Register("TriggersLabel", typeof(string), typeof(MainWindow), new PropertyMetadata("Triggers"));


        public string NumSelectedRow
        {
            get { return (string)GetValue(NumSelectedRowProperty); }
            set { SetValue(NumSelectedRowProperty, value); }
        }

        // Using a DependencyProperty as the backing store for NumSelectedRow.  This enables animation, styling, binding, etc...
        public static readonly DependencyProperty NumSelectedRowProperty =
            DependencyProperty.Register("NumSelectedRow", typeof(string), typeof(MainWindow), new PropertyMetadata(""));




        public string QueryTime
        {
            get { return (string)GetValue(QueryTimeProperty); }
            set { SetValue(QueryTimeProperty, value); }
        }

        // Using a DependencyProperty as the backing store for QueryTime.  This enables animation, styling, binding, etc...
        public static readonly DependencyProperty QueryTimeProperty =
            DependencyProperty.Register("QueryTime", typeof(string), typeof(MainWindow), new PropertyMetadata(String.Empty));




        public string StatusMessage
        {
            get { return (string)GetValue(StatusMessageProperty); }
            set { SetValue(StatusMessageProperty, value); }
        }

        // Using a DependencyProperty as the backing store for StatusMessage.  This enables animation, styling, binding, etc...
        public static readonly DependencyProperty StatusMessageProperty =
            DependencyProperty.Register("StatusMessage", typeof(string), typeof(MainWindow), new PropertyMetadata(String.Empty));




        #endregion

        private void OpenFiles()
        {
            // Configure open file dialog box
            Microsoft.Win32.OpenFileDialog dlg = new Microsoft.Win32.OpenFileDialog();
            dlg.FileName = ""; // Default file name

            dlg.Filter = "sqlite files (*.sqlite)|*.sqlite|db files (*.db)|*.db*|All files (*.*)|*.*";
            dlg.DefaultExt = "*.*"; // Default file extension
            dlg.FilterIndex = 3;
            dlg.Multiselect = false;
            dlg.InitialDirectory = @"D:\SqLiteEditor\SampleDb";//AppDomain.CurrentDomain.BaseDirectory;


            // Process open file dialog box results 
            if (dlg.ShowDialog().GetValueOrDefault())
            {
                FullFileNames = dlg.FileName;
                OpenDataBase(FullFileNames, dlg.SafeFileName);

            }
        }

        private void OpenDataBase(string fullfilename, string filename, bool NewDataBase = false)
        {
            SqliteHelper.Connect(fullfilename, NewDataBase);

            DBFileName = filename;

            DataRowCollection tabels = SqliteHelper.GetTabels();
            TabelsLabel = "Tabels (" + tabels.Count.ToString() + ")";

            foreach (DataRow tabel in tabels)
            {
                string CurrTableName = tabel.ItemArray[2].ToString();

                TreeViewItem treeViewItem = new TreeViewItem();
                treeViewItem.Header = CurrTableName;
                treeViewItem.Tag = tabel;
                treeViewItem.ContextMenu = (ContextMenu)Resources["TabelContextMenu"];
                treeViewItem.ContextMenu.Tag = CurrTableName;

                int index = PART_Tabels.Items.Add(treeViewItem);

                Tabels.Add(tabel.ItemArray[2].ToString());

                List<TTabelStructure> columnFieldType = SqliteHelper.GetColumnFieldType(CurrTableName);

                TableDML.Add(tabel.ItemArray[2].ToString(), SqliteHelper.GetDML(tabel));

                foreach (TTabelStructure fieldInfo in columnFieldType)
                {
                    TreeViewItem fieldInfoitem = new TreeViewItem();
                    //fieldInfoitem.Template = 
                    fieldInfoitem.Header = fieldInfo.ToString();
                    fieldInfoitem.Tag = fieldInfo;

                    treeViewItem.Items.Add(fieldInfoitem);
                }
            }

            DataRowCollection views = SqliteHelper.GetViews();

            ViewsLabel = "Views (" + views.Count.ToString() + ")";

            foreach (DataRow view in views)
            {
                Views.Add(view.ItemArray[2].ToString());

                TreeViewItem viewItem = new TreeViewItem();
                viewItem.Header = view.ItemArray[2].ToString();
                viewItem.Tag = view;
                viewItem.ContextMenu = (ContextMenu)Resources["ViewContextMenu"];
                PART_Views.Items.Add(viewItem);

            }

            DataRowCollection indexes = SqliteHelper.GetIndexes();

            IndexesLabel = "Indexes (" + indexes.Count.ToString() + ")";

            foreach (DataRow index in indexes)
            {
                Indexes.Add(index.ItemArray[5].ToString());

                TreeViewItem fieldInfoitem = new TreeViewItem();
                fieldInfoitem.Header = index.ItemArray[5].ToString();
                fieldInfoitem.Tag = index;
                fieldInfoitem.ContextMenu = (ContextMenu)Resources["IndexContextMenu"];
                PART_Indexes.Items.Add(fieldInfoitem);

            }

            DataRowCollection triggers = SqliteHelper.GetTriggers();

            TriggersLabel = "Triggers (" + triggers.Count.ToString() + ")";

            foreach (DataRow trigger in triggers)
            {
                Indexes.Add(trigger.ItemArray[2].ToString());
            }

            tb_Version.Text = SqliteHelper.SqliteVersion;
        }

        private void Log(string message)
        {
            //this.MessageEdittor.Clear();
            //this.MessageEdittor.Text = message;
        }

        private void InsertQuerytoQueryEditor(string query)
        {
            //QueryEdittor.Text = query;
            //NumSelectedRow = SqliteDataGrid.Items.Count.ToString() + " Rows";
            //MainTabCtrl.SelectedIndex = 1;
        }

        private void ExecuteCurrentQuery()
        {

            var firstDocumentPane = dockManager.Layout.Descendents().OfType<LayoutDocumentPane>().FirstOrDefault();

            if (firstDocumentPane != null)
            {

                object obj = firstDocumentPane.SelectedContent;

                if (obj is TBrowsWindow)
                {

                    string query = (obj as TBrowsWindow).QueryEdittor.Text;

                    (obj as TBrowsWindow).SqliteDataGrid.ItemsSource = SqliteHelper.ExecutQuery(query).DefaultView;

                    QueryTime = SqliteHelper.LastExecuteTime;

                }
            }
        }

        private void ExecuteNonQuery()
        {
            // string query = QueryEdittor.Text;

            // SqliteHelper.ExecuteNonQuery(query);

            // QueryTime = SqliteHelper.LastExecuteTime;

            // NumSelectedRow = "";
        }

        private string GetCurrentSelectedtable()
        {
            return (string)((DataRow)((MainTree.SelectedItem as TreeViewItem).Tag)).ItemArray[2];
        }

        private string GetCurrentSelectedIndex()
        {
            return (string)((DataRow)((MainTree.SelectedItem as TreeViewItem).Tag)).ItemArray[5];
        }

        private string GetCurrentSelectedView()
        {
            return (string)((DataRow)((MainTree.SelectedItem as TreeViewItem).Tag)).ItemArray[2];
        }

        private void DesignTable()
        {
            string TabelName = GetCurrentSelectedtable();

            var firstDocumentPane = dockManager.Layout.Descendents().OfType<LayoutDocumentPane>().FirstOrDefault();
            if (firstDocumentPane != null)
            {

                LayoutDocument laydoc = new LayoutDocument();
                laydoc.Title = TabelName + " Design " + (firstDocumentPane.Children.Count + 1).ToString();

                TStructureWindow StructureWindow = new TStructureWindow();
                StructureWindow.QueryEdittor.Text = TableDML[TabelName];

                StructureWindow.GetDesignTable(TabelName);

                laydoc.Content = StructureWindow;

                firstDocumentPane.Children.Add(laydoc);

                QueryTime = SqliteHelper.LastExecuteTime;

            }

        }

        private void SelectTopn()
        {
            //Get Current Selected Table
            string TabelName = GetCurrentSelectedtable();

            string query = "SELECT * FROM " + TabelName + ";";


            var firstDocumentPane = dockManager.Layout.Descendents().OfType<LayoutDocumentPane>().FirstOrDefault();
            if (firstDocumentPane != null)
            {

                LayoutDocument laydoc = new LayoutDocument();
                laydoc.Title = TabelName + " Query " + (firstDocumentPane.Children.Count + 1).ToString();

                TBrowsWindow BrowsWindow = new TBrowsWindow(query);
                BrowsWindow.QueryEdittor.Text = query;

                laydoc.Content = BrowsWindow;

                firstDocumentPane.Children.Add(laydoc);

                QueryTime = SqliteHelper.LastExecuteTime;

                //  NumSelectedRow = SqliteDataGrid.Items.Count.ToString() + " Rows";
            }

        }


        private void EditData()
        {
            //Get Current Selected Table
            string TabelName = GetCurrentSelectedtable();

            string query = "SELECT * FROM " + TabelName + ";";


            var firstDocumentPane = dockManager.Layout.Descendents().OfType<LayoutDocumentPane>().FirstOrDefault();
            if (firstDocumentPane != null)
            {

                LayoutDocument laydoc = new LayoutDocument();
                laydoc.Title = TabelName + " Query " + (firstDocumentPane.Children.Count + 1).ToString();

                TEditWindow EditWindow = new TEditWindow();
                DataTable data = SqliteHelper.ExecutQuery(query);
                EditWindow.DataTable = data;
                EditWindow.SqliteDataGrid.ItemsSource = data.DefaultView;

                laydoc.Content = EditWindow;
                firstDocumentPane.Children.Add(laydoc);

                QueryTime = SqliteHelper.LastExecuteTime;
            }

        }


        private void dockManager_DocumentClosing(object sender, DocumentClosingEventArgs e)
        {
            if (MessageBox.Show("Are you sure you want to close the document?", "Warning !", MessageBoxButton.YesNo) == MessageBoxResult.No)
                e.Cancel = true;
        }

        private void avalonObjectExplorer_PropertyChanged(object sender, System.ComponentModel.PropertyChangedEventArgs e)
        {
            if (e.PropertyName == "IsVisible" && avalonObjectExplorer.IsVisible)
            {
                avalonObjectExplorer.Show();
            }
        }

        private void ShowAbout()
        {
            TAbout about = new TAbout();
            about.Show();
        }

    }
}
